<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <!-- <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="addInOrOut"
        >新增</el-button> -->
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
      title="新增"
      :visible.sync="showAdd"
      @close="showAdd = false"
      width="35%"
    >
        <el-form :model="createForm" :inline="true" ref="createForm" :rules="addRules">
            <el-form-item label="条码" prop="code" >
                <el-input v-model="createForm.code" autosize style="width: 150px"/>
            </el-form-item>
            <el-form-item>
                <el-button type="success" @click="codeHuoqu">获取</el-button>
            </el-form-item>
            <!-- <el-form-item label="点检内容" prop="content" >
                <el-input v-model="createForm.content" autosize style="width: 300px"/>
            </el-form-item> -->
        </el-form>
        <el-table :data="AddForm" stripe border style="margin-bottom: 10px;">
          <el-table-column  label="序号" type="index" align="center" width="80px"/>
          <el-table-column prop="code" align="center" label="代码" />
          <el-table-column prop="content" align="center" label="点检、保养内容" />
          <el-table-column align="center" label="操作"  width="180">
            <template slot-scope="scope" >
                {{ scope.row.isAccomplish == 1 ? '失败' : '成功' }}
            </template>
          </el-table-column>
        </el-table>
        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
            >新增</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->
        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px"
            :style="{ width: inputWid(param.facilityBarcode) }"
            v-model="param.facilityBarcode"
            placeholder="条码"
        ></el-input>

        <el-select
            v-model="param.facilityBarcodeType1" 
            autosize 
            style="margin-right: 15px;width: 150px"
            class="ul-item"
            filterable
            clearable
            placeholder="资源大类"
            @focus="getBarcodeType('大类')">
            <el-option
                v-for="(item,index) in barcodeType1List"
                :key="index"
                :label="item.facilityBarcodeChineseName"
                :value="item.facilityBarcodeName">
            </el-option>
        </el-select>

        <el-select
        v-model="param.facilityBarcodeType2" autosize  style="margin-right: 15px;width: 150px"
              class="ul-item"
              filterable
              clearable
              placeholder="资源小类"
              @focus="getBarcodeType('小类')">
              <el-option
                  v-for="(item,index) in barcodeType2List"
                  :key="index"
                  :label="item.facilityBarcodeChineseName"
                  :value="item.facilityBarcodeName">
              </el-option>
          </el-select>

          <el-select
          v-model="param.facilityBarcodeType3" autosize style="margin-right: 15px;width: 150px"
              class="ul-item"
              filterable
              clearable
              placeholder="资源规格"
              @focus="getBarcodeType('规格')">
              <el-option
                  v-for="(item,index) in barcodeType3List"
                  :key="index"
                  :label="item.facilityBarcodeChineseName"
                  :value="item.facilityBarcodeName">
              </el-option>
          </el-select>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px;width: 150px"
            v-model="param.jobNumber"
            placeholder="操作人员"
        ></el-input>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px;width: 150px"
            v-model="param.type"
            placeholder="类别"
        ></el-input>

        <el-select style="margin-right: 15px;width: 150px" clearable filterable v-model="param.workCenter" placeholder="请选择工作中心" @focus="getCenterList" class="ul-item">
          <el-option :value="item" :label="item" v-for="(item,index) in this.centerList.data" :key="index"/>
        </el-select>

        <el-date-picker
          v-model="dateOptions"
          type="datetimerange"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm:ss"
          align="right"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :picker-options="pickerOptions"
          style="margin-right:10px;">
        </el-date-picker>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border  highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="条码"  prop="facilityBarcode" align="center"/>
      <el-table-column label="大类"  prop="facilityBarcodeType1" align="center"/>
      <el-table-column label="小类"  prop="facilityBarcodeType2" align="center"/>
      <el-table-column label="名称"  prop="facilityName" align="center"/>
      <el-table-column label="规格型号"  prop="facilityBarcodeType3" align="center"/>
      <el-table-column label="工作中心"  prop="workCenter" align="center"/>
      <el-table-column label="存放位置"  prop="warehouseLocation" align="center"/>
      <el-table-column label="点检\保养人员"  prop="spotJobNumber" align="center"/>
      <el-table-column label="是否完成"  prop="isAccomplish" align="center">
        <template slot-scope="scope" >
                {{ scope.row.isAccomplish == 1 ? '失败' : '成功' }}
            </template>
      </el-table-column>
      <el-table-column label="类别"  prop="type" align="center"/>
      <!-- <el-table-column label="点检\保养周期"  prop="maintenanceFrequency" align="center"/> -->
      <el-table-column label="点检\保养周期"  prop="createTime" align="center" width="140"/>
      <el-table-column label="图片" prop="img" align="center">
        <template slot-scope="scope" >
            <el-image v-for="(item, index) in scope.row.img" :key='index' style="width: 30px; height: 30px" :src="item" :preview-src-list="scope.row.img" fit="scale-down">
                <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                </div>
            </el-image>
        </template>
      </el-table-column>
      <!-- <el-table-column label="点检\保养时间"  prop="maintenanceTime" align="center"/> -->
      <el-table-column label="点检\保养时间"  prop="updateTime" align="center" width="140"/>
      <el-table-column label="操作" fixed="right" align="center" width="130">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button size="mini" type="success" @click="handleEdit(scope.row)">查看</el-button>
                    <el-button
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>

    <!-- 修改数据弹窗 -->
    <el-dialog
      title="设备点检\保养记录"
      :visible.sync="showupd"
      @close="showupd = false"
      width="40%"
    >
    <el-descriptions size="medium" border style="margin-bottom: 10px;">
        <el-descriptions-item label="编号">{{ updForm.length ? updForm[0].facilityBarcode : '' }}</el-descriptions-item>
        <el-descriptions-item label="大类">{{ updForm.length ? updForm[0].facilityBarcodeType1 : '' }}</el-descriptions-item>
        <el-descriptions-item label="小类">{{ updForm.length ? updForm[0].facilityBarcodeType2 : '' }}</el-descriptions-item>
        <el-descriptions-item label="名称">{{ updForm.length ? updForm[0].facilityName : '' }}</el-descriptions-item>
        <el-descriptions-item label="型号">{{ updForm.length ? updForm[0].facilityBarcodeType3 : '' }}</el-descriptions-item>
        <el-descriptions-item label="位置">{{ updForm.length ? updForm[0].warehouseLocation : '' }}</el-descriptions-item>
        <el-descriptions-item label="部门">{{ updForm.length ? updForm[0].workCenter : '' }}</el-descriptions-item>
        <el-descriptions-item label="类型">{{ updForm.length ? updForm[0].type : '' }}</el-descriptions-item>
        <el-descriptions-item label="日期">{{ updForm.length ? updForm[0].maintenanceTime : '' }}</el-descriptions-item>
    </el-descriptions>

    <el-table :data="updForm" stripe border style="margin-bottom: 10px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column prop="content" align="center" label="点检、保养内容" />
      <el-table-column prop="isAccomplish" align="center" label="结果"  width="180">
        <template slot-scope="scope" >
            {{ scope.row.isAccomplish == 1 ? '失败' : '成功' }}
        </template>
      </el-table-column>
    </el-table>

    <div class="demo-image__placeholder">
  <div class="block" style="display: flex;">
    <div>
        <el-image  style="width: 300px; height: 300px" :src="updForm.length ? updForm[0].img : ''"></el-image>
    </div>
    <div>
        <el-descriptions style="margin: 100px 0 0 20px;" size="medium">
            <el-descriptions-item label="点检\保养人">{{ updForm.length ? updForm[0].userName : '' }}</el-descriptions-item>
        </el-descriptions>
        <div style="margin: 130px 0 0 10px;">
            <el-select
                v-model="util" 
                placeholder="类型"
                style="margin-right: 20px;width: 100px"
                >
                <el-option 
                :value="item" 
                :label="item" v-for="(item,index) in this.printerTypeList" 
                :key="index"/>
            </el-select>
            <el-select
                clearable
                v-model="printerName" 
                placeholder="请选择打印机"
                style="margin-right: 20px"
                >
                <el-option 
                :value="item" 
                :label="item" v-for="(item,index) in this.printerNameList" 
                :key="index"/>
            </el-select>
        </div>
</div>
</div>
</div>


        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showupd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="updprocess('updForm')"
            >打印</el-button
            >   
        </div>
    </el-dialog>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>
    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template>

<script>
import { resourceFind,facilitySel,maintenanceAdd,maintenanceWord03,maintenancefindGroup,maintenanceSel,configurationAdd,configurationUpd,configurationDel,selbarcodeType } from "@/api/processRoute"
import { findZplPrinterInfoList } from '../../api/orderAndMachine'
import { getCenter } from '../../api/workSection.js'
export default {
    name: 'maintenanceRecord',
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                code: '',                      
                content: ''                    
            },
            total: 0,                                      //数据的总数
            tableInfo: [],
            AddForm:[],
            centerList: {data:[]}, 
            tableMX:[],
            showMX: false,
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {},
            updForm: {},
            props: { multiple: true },
            // 表单校验
            addRules: {
                code: [
                    { required: true, message: "条码不能为空!", trigger: "change" },
                ],
                content: [
                    { required: true, message: "点检内容不能为空!", trigger: "change" },
                ],
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            barcodeType1List: [],
            accessTypeList: ['出库','入库'],
            printerTypeList: ['单面','双面'],
            printerName: '',
            util: '双面',
            printerNameList: [],
            barcodeType2List: [],
            barcodeType3List: [],
            dateOptions: this.getNowTime(),
            pickerOptions: {                            // 选择时间范围
              shortcuts: [{
                text: '最近一周',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近一个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
                  picker.$emit('pick', [start, end]);
                }
              }, {
                text: '最近三个月',
                onClick(picker) {
                  const end = new Date();
                  const start = new Date();
                  start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
                  picker.$emit('pick', [start, end]);
                }
              }]
            },
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        async codeHuoqu(){
            if(!this.createForm.code) return this.$message.warning('条码不能为空!')
            let query = {
                facilityBarcode: this.createForm.code,
                page: 1,
                limit: 10
            }
            const res1 = await facilitySel(query)
            console.log(res1.data.records)
            if(!res1.data.records.length) return this.$message.warning('请输入正确条码!')
            let query2 = {
                page: 1,
                limit: 10,
                facilityBarcodeType1: res1.data.records[0].facilityBarcodeType1,
                facilityBarcodeType2: res1.data.records[0].facilityBarcodeType2,
                facilityBarcodeType3: res1.data.records[0].facilityBarcodeType3
            }
            const res2 = await resourceFind(query2)
            console.log(res2.data.list[0].code)
            let arr1
            let arr2
            if(res2.data.list[0].code){
                arr1 = res2.data.list[0].code.split(",")
            }
            if(res2.data.list[0].content){
                arr2 = res2.data.list[0].content.split(",")
            }
            console.log(arr1)
            console.log(arr2)
            console.log(this.AddForm)
        },
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async getBarcodeType(type) {
            this.loadingList = true
            let query = {
                facilityBarcodeType: type,
                page: 1,
                limit: 10000
            }
            let data = await selbarcodeType(query)
            let errmsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            if(type == '大类'){
                this.barcodeType1List = data.data.records
            } else if(type == '小类') {
                this.barcodeType2List = data.data.records
            } else if(type == '规格') {
                this.barcodeType3List = data.data.records
            }
            this.loadingList = false
        },
         // 获取工作中心
      async getCenterList() {
        let query = {}
        const data = await getCenter(query)
        this.centerList = data
      },
      //初始默认执行(重点)，返回日期格式YYYY-MM-DD HH:MM:SS
      getNowTime() {
        let dateTime = +new Date()+8*3600*1000
        const start = new Date(dateTime - 3600 * 1000 * 24 * 7)
            .toISOString()
            .replace('T', ' ')
            .split('.')[0]
            // .substring(0,10) //默认开始时间7天前
        const end = new Date(dateTime)
            .toISOString()
            .replace('T', ' ')
            .split('.')[0]
            // .substring(0,10)//默认结束时间当前时间
        console.log([start, end])
        return [start, end]
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery,this.param)
            let data = await maintenancefindGroup(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.count
            this.tableInfo = data.data.list
            this.tableInfo.forEach(item => {
                  item.img = this.cuttingStr(item.img)
                  
                });
        },
        // 切割图片url组成的字符串成为数组
        cuttingStr(value) {
          console.log(value)
            let imageArr = []                           //存储图片url的数组
            if(value != '' && value != null) {                           //第一层嵌套判断是否有图片，为空直接返回一个空数组
                if(value.includes('|')){
                  imageArr = value.split('|')             //第二层嵌套将图片拆分为数组
                } else{
                  imageArr.push(value)
                }
                return imageArr
            } else {
                return imageArr
            }
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            facilityBarcode: '条码',
            facilityBarcodeType1: '大类',
            facilityBarcodeType2: '小类',
            facilityName: '名称',
            facilityBarcodeType3: '规格型号',
            workCenter: '工作中心',
            warehouseLocation: '存放位置',
            spotJobNumber: '点检\保养人员',
            isAccomplish: '是否完成',
            type: '类别',
            maintenanceFrequency: '点检\保养周期',
            img: '图片',
            maintenanceTime: '点检\保养时间',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },
        async delprocess(row,index){
          let res = await configurationDel({id: row.id})
          if(res.code == '500') return
          if(res.code != '1') return this.$message.error(res.msg)
          this.tableInfo.splice(index,1)
          this.$message.success(res.msg)
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery,this.param)
          query.page = 1
          query.limit = 10000
          let arr = await maintenancefindGroup(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.list.length){
            this.loading = false
            this.$message.error('暂无数据')
          }
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '检点/保养记录', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              facilityBarcode: item.facilityBarcode,
              facilityBarcodeType1: item.facilityBarcodeType1,
              facilityBarcodeType2: item.facilityBarcodeType2,
              facilityName: item.facilityName,
              facilityBarcodeType3: item.facilityBarcodeType3,
              workCenter: item.workCenter,
              warehouseLocation: item.warehouseLocation,
              spotJobNumber: item.spotJobNumber,
              isAccomplish: item.isAccomplish == 1 ? '失败' : '成功',
              type: item.type,
              maintenanceFrequency: item.maintenanceFrequency,
              img: item.img,
              maintenanceTime: item.maintenanceTime,
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {
                code: '',           
                content: '',      
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        async submitprocess(){
            let query = Object.assign({},this.createForm)
            const data = await configurationAdd(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        resetForm(){
             this.$refs.createForm.resetFields();
        },
        async handleEdit(row){
            // this.updForm = Object.assign({},row)
            let query = {
                type: row.type,
                facilityBarcode: row.facilityBarcode,
                facilityBarcodeType1: row.facilityBarcodeType1,
                facilityBarcodeType2: row.facilityBarcodeType2,
                facilityName: row.facilityName,
                facilityBarcodeType3: row.facilityBarcodeType3,
                timeId: row.timeId,
                page: 1,
                limit: 10000,
            }
            const res = await maintenanceSel(query)
            console.log(res)
            this.updForm = res.data.list
            this.showupd = true
        },
        // 提交表单之前先进行验证
        updprocess(formName) {
                    this.configurationUpd()
        },
        async configurationUpd(){
            // let query = Object.assign({},this.updForm[0])
            if(!this.printerName) return this.$message.error('请选择打印机！')
            let  emsFacilityMaintenance = {
                    facilityBarcode: this.updForm[0].facilityBarcode,
                    facilityBarcodeType1: this.updForm[0].facilityBarcodeType1,
                    facilityBarcodeType2: this.updForm[0].facilityBarcodeType2,
                    facilityName: this.updForm[0].facilityName,
                    facilityBarcodeType3: this.updForm[0].facilityBarcodeType3,
                    lendingPosition: this.updForm[0].lendingPosition,
                    workCenter: this.updForm[0].workCenter,
                    type: this.updForm[0].type,
                    img: this.updForm[0].img,
                    createTime: this.updForm[0].createTime,
            }
            let query = {
                util: this.util == '双面'?'双':'单',
                printerName: this.printerName,
                emsFacilityMaintenance: emsFacilityMaintenance
            }
            console.log(query)
            const data = await maintenanceWord03(query)
            const errMsg = data.msg
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.showupd = false
            this.handleFilter()
            this.$message.success(errMsg)
        },
        async getPrinter(){
            const data = await findZplPrinterInfoList()
            if(data.code == '1'){
                console.log('data',data);
                this.printerNameList = JSON.parse(JSON.stringify(data.data))
                this.printerNameList.forEach((item,index) =>{
                    if(item.indexOf('\\\\')>=0){
                       this.printerNameList[index] = item.split('\\')[3]
                    }
                })
                console.log(this.printerNameList)
            }
        },
        addInOrOut(){
            this.showAdd = true
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
        this.getPrinter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
